package com.shujia.scala

object Demo21Match {
  def main(args: Array[String]): Unit = {

    /**
      * java中的匹配，只能匹配，基本数据类型，字符串，枚举
      *
      * scala模式匹配可以匹配，基本数据类型，字符串，对象，类型的匹配
      *
      *
      */

    //1、匹配字符串

    val str: String = "hadoop"

    str match {
      case "java" => println("这是java")
      case "spark" => println("这是spark")
      case _ => println("其它")
    }


    //匹配基本数据类型

    val i: Int = 100

    i match {
      case 100 => println("100")
      case 200 => println("200")
      case _ => println("其它")
    }


    //3\、匹配对象
    val user = User("001", "张三", 24)

    user match {
      case User("001", "张三", 23) => println("张三")
      case User("002", "李四", 24) => println("李四")
      case _ => println("其它")
    }


    //4、匹配类型
    val s: Any = 1.1


    s match {
      case i: Int => println("int类型")
      case s: String => println("字符串")
      case _ => println("其它类型")
    }



    //模式匹配可以有返回值


    val age: Int = 23

    val r: String = age >= 18 match {
      case true => "成年"
      case false => "未成年"
    }


    println(r)


    val map = Map("001" -> "张三", "002" -> "李四")



    println(map("001"))
    println(map.getOrElse("003", "默认值"))

    /**
      * get : 如果key存在返回some, r如果key不存在返回node
      *
      *
      * 解决空指针异常
      */

    val value: String = map.get("003") match {
      case Some(v) => v
      case None => "默认值"
    }


  }

  case class User(id: String, name: String, age: Int)

}


